<template>
  <div class="content">
    <el-button type="primary" @click="handleAddUser">+ 添加用户</el-button>
    <!-- 用户抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="30%" direction="rtl">
      <el-form class="form-inline" :model="formData.sysUser" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="formData.sysUser.userName" placeholder="请输入用户账号" clearable :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!isEdit">
          <el-input v-model="formData.sysUser.password" placeholder="请输入用户密码" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.sysUser.nickname" placeholder="请输入用户昵称" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户手机号" prop="phone">
          <el-input v-model="formData.sysUser.phone" placeholder="请输入用户手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.sysUser.remark" type="textarea" placeholder="请输入备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.sysUser.state">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属角色" prop="roleIds">
          <el-select v-model="formData.roleIds" placeholder="请选择所属角色" multiple>
            <el-option v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-button">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 用户表格 -->
    <el-table :data="dataList" style="width: 100%;margin-top: 20px;" row-key="id">
      <el-table-column prop="userName" label="用户账号"></el-table-column>
      <el-table-column prop="nickname" label="用户昵称"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="gender" label="性别">
        <template #default="{ row }">
          <el-tag :type="row.gender === 0 ? 'success' : 'danger'">
            {{ row.gender === 0 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.state === 0 ? 'success' : 'danger'">
            {{ row.state === 0 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="loginIp" label="登录Ip"></el-table-column>
      <el-table-column prop="loginTime" label="最后登录时间"></el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="pageSize" :current-page="currentPage"
        layout="total, prev, pager, next, sizes, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { UserPageResponse, getUserPageListAPI, addUserAPI, updateUserAPI, deleteUserAPI} from '@/api/user'
import { getAllRolesAPI, getUserRoleListAPI } from '@/api/role'
import type { SysUser, UserItem, RoleItem } from '@/types'


// 用户数据
const dataList = ref<SysUser[]>([])

// 用户抽屉
const drawerVisible = ref(false)
const drawerTitle = ref('添加用户')
const isEdit = ref(false)

const formRef = ref<FormInstance>()
const formData = reactive<UserItem>({
  sysUser: {
    id: '',
    userName: '',
    password: '',
    nickname: '',
    phone: '',
    gender: 0,
    remark: '',
    state: 0
  },
  roleIds: [] as string[]
})

// 角色列表
const roleList = ref<RoleItem[]>([])

const validatePass2 = (rule, value, callback) => {
  if (formData.roleIds?.length == 0) {
    callback(new Error('请选择角色'));
  }
  callback();
};
// 表单验证规则
const formRules: FormRules = {
  userName: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    ...(isEdit.value ? [] : [
      { min: 3, max: 20, message: '用户账号长度在 3 到 20 个字符', trigger: 'blur' }
    ])
  ],
  password: isEdit.value
    ? [] // 编辑模式不验证密码
    : [
      { required: true, message: '请输入用户密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
}
// 添加用户
const handleAddUser = () => {
  drawerTitle.value = '添加用户'
  isEdit.value = false
  handleReset()
  drawerVisible.value = true
}
// 编辑用户
const handleEdit = async (row: SysUser) => {
  drawerTitle.value = '编辑用户'
  isEdit.value = true
  drawerVisible.value = true
  // 深拷贝用户数据，避免直接修改原始数据
  formData.sysUser = { ...row }
  // 单独处理角色ID
  try {
    const { result } = await getUserRoleListAPI<Array<RoleItem>>(row.id!)
    formData.roleIds = result!.map(role => role.id ?? '')
  } catch (error) {
    // 获取失败时的降级处理
    console.error('获取用户角色失败', error)
    formData.roleIds = []
    ElMessage.warning('用户角色信息获取失败，可能影响编辑功能')
  }

}
// 删除用户
const handleDelete = async (row: SysUser) => {
  try {
    await ElMessageBox.confirm('确定删除该用户吗？', '提示', {
      type: 'warning'
    })
    await deleteUserAPI(row.id!)
    ElMessage.success('删除成功')
    loadUserList()
  } catch (error) {
    console.log("删除取消或出错:", error)
  }
}
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  try {
    if (isEdit.value) {
      await updateUserAPI(formData);
      ElMessage.success('修改成功');
    } else {
      await addUserAPI(formData);
      ElMessage.success('添加成功');
    }

    drawerVisible.value = false
    loadUserList()
  } catch (error) {
    ElMessage.error('操作失败')
    console.log('操作失败:', error)
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: '',
    userName: '',
    password: '',
    nickname: '',
    phone: '',
    gender: 0,
    remark: '',
    state: 0,
    roleIds: []
  })
}
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadUserList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadUserList()
}
// 加载用户列表
const loadUserList = async () => {
  try {
    const response: UserPageResponse = await getUserPageListAPI({
      page: currentPage.value,
      pageSize: pageSize.value
    })

    if (response.code === 200) {
      dataList.value = response.result?.dataList || []
      total.value = response.result?.pageTotal || 0
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  }
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    const response = await getAllRolesAPI()
    if (response.code === 200) {
      roleList.value = response.result || []
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
  }
}

// 初始化
onMounted(() => {
  loadUserList()
  loadRoleList()
})
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
  font-size: 14px;
  background-color: #ffffff;
  padding: 20px;
}

:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #101010;
  font-weight: 600;
  text-align: center;
}

:deep(.el-table td) {
  padding: 12px 0;
  text-align: center;
}

:deep(.el-button) {
  margin-right: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
